var soap = require('./soap');
var rpt = require('./report');
var https = require('https');
var $ = require('jquery');
var ET = require('elementtree');
var bingProperties = require('./bingProperties');
var SOAP = bingProperties.SOAP;
var STATIC = bingProperties.STATIC;
var fs = require('fs');

var HOST = 'adcenterapi.microsoft.com';
var PROTOCOL = 'https://';
// var APIVERSION = '/api/advertiser/v8/';
var APIVERSION = '/Api/Advertiser/v8/';
var downloadPath = bingProperties.downloadPath;

var URI = PROTOCOL + HOST + APIVERSION;
// https://adcenterapi.microsoft.com/Api/Advertiser/v8/Reporting/ReportingService.svc?wsdl
var BINGMODEL = {
    CampaignManagementService: APIVERSION + 'CampaignManagement/CampaignManagementService.svc?wsdl',
    SubmitGenerateReport: APIVERSION + 'Reporting/ReportingService.svc?wsdl'
};



exports.campaignManagement = {};
exports.Reporting = function() {};
exports.Reporting.prototype.reportingService = function(soapAction, soapReport) {
    var self = exports.Reporting.reportingService;
    var soapHeader = soapReport.toXMLString();
    var customerAccountId = soapReport.root.findtext('.//CustomerAccountId');
    var developerToken = soapReport.root.findtext('.//DeveloperToken');
    var password = soapReport.root.findtext('.//Password');
    var userName = soapReport.root.findtext('.//UserName');
    var action = soapReport.root.findtext('.//Action');
    //===================================
    var str = fs.readFileSync('./soapXML/bulk2.xml');
    console.log(str.toString())
    soapHeader = str.toString();
    //===================================
    // console.log(customerAccountId, developerToken, password, userName, action);
    // console.log(action,BINGMODEL);
    var sconf = {
        host: HOST,
        path: BINGMODEL[soapAction],
        method: 'POST',
        headers: {
            'Content-type': 'text/xml; charset="utf-8"',
            'Content-length': soapHeader.length,
            SOAPAction: soapAction
        }
    };

    // 
    // var soapHeader = fs.readFileSync('./soapXML/t3.xml', 'utf-8').toString();
    // console.log('soapHeader',soapHeader);
    soap.send(sconf, soapHeader, function(err, data) {
        console.log('========================\n',data);
        if(!err) {
            var s = function() {
                    var xmlTree = ET.parse(data.toString());
                    var reportRequestId = xmlTree.findtext('.//ReportRequestId');
                    var pollRequest = new rpt.PollReportRequest();
                    var pAction = 'PollGenerateReport';
                    pollRequest.setCustomerAccountId(customerAccountId);
                    pollRequest.setDeveloperToken(developerToken);
                    pollRequest.setPassword(password);
                    pollRequest.setUserName(userName);
                    pollRequest.setAction(pAction);
                    pollRequest.setReportRequestId(reportRequestId);
                    // console.log('down load reportRequestId', reportRequestId)
                    pHeader = pollRequest.toXMLString();
                    var pConf = $.extend({}, sconf);
                    pConf.headers['Content-length'] = pHeader.length;
                    pConf.headers.SOAPAction = pAction;
                    // console.log(soapHeader);
                    var statusFlag = ''; //Error/Pending/Success
                    var t;
                    soap.send(pConf, pHeader, function(err, data) {
                        // console.log('pHeader', pHeader)
                        if(!err) {
                            var xtree = ET.parse(data.toString());
                            statusFlag = xtree.findtext('.//Status');
                            switch(statusFlag) {
                            case 'Success':
                                var url = xtree.findtext('.//ReportDownloadUrl');
                                // console.log(url);
                                https.get(url, function(res) {
                                    var fileNameReg = /\w+\.zip/;
                                    // console.log("<><><><><><><><><><><><><><><><><>", res.headers['content-disposition']);
                                    var fileName = res.headers['content-disposition'].split('"')[1];
                                    var downloadStream = fs.createWriteStream(downloadPath + fileName);
                                    res.pipe(downloadStream);
                                    soapReport.emit('reportDataReady', url);
                                    downloadStream.on('close', function() {
                                        soapReport.emit('reportDataComplete', downloadPath + fileName);
                                    })
                                    // console.log(fileName);
                                });

                                // clearInterval(t);
                                break;
                            case 'Pending':
                                setTimeout(s, 1000);
                                break;
                            case 'Error':
                                // clearInterval(t);
                                break;
                            default:
                                break;
                            }
                            // console.log(2222222222222,err, data.toString(),xtree.findtext('.//Status'),statusFlag);
                        } else {
                            console.log(err.xml.toString());
                        }
                    });
                };
            s();

            // console.log(pollRequest.toXMLString());
        } else { //error
            err.header = soapReport.toXMLString();
            soapReport.emit('reportError', err);
        }

    });

};



exports.campaignManagement.campaignManagementService = function(action, customerAccountId, developerToken, password, userName, callback) {
    var self = exports.campaignManagement.campaignManagementService;
    var customerId = '';
    var applicationToken = '';
    // var soapHeader = self.getCampaignManagementServiceHeader(action, customerAccountId, developerToken, password, userName, applicationToken, customerId);
    var soapHeader = self.getCampaignManagementServiceHeader(action, customerAccountId, developerToken, password, userName, applicationToken, customerId);
    // console.log(jQuery.extend(true));
    var sconf = $.extend(true, SOAPCONF, {
        path: BINGMODEL['CampaignManagementService'],
        headers: {
            'Content-length': soapHeader.length,
            SOAPAction: action
        }
    });
    self.send = function(callback) {
        // console.log('soapHeader',soapHeader);
        soap.send(sconf, soapHeader, callback);
    };
    if(callback) {
        self.send(callback);
    }
    return self;
};

exports.campaignManagement.campaignManagementService.getCampaignManagementServiceHeader = function(action, customerAccountId, developerToken, password, userName, applicationToken, customerId) {
    if(!action || !customerAccountId || !developerToken || !password || !userName) {
        console.log(
        arguments);
        throw new Error('campaignManagementService error! Missing required parameters');
    }
    var root = ET.Element('s:Envelope');
    root.set('xmlns:i', SOAP.ns_xsi);
    root.set('xmlns:s', SOAP.ns_soapenv);
    var header = ET.SubElement(root, 's:Header');
    header.set('xmlns', SOAP.ns_bingads);
    var appToken = ET.SubElement(header, 'ApplicationToken');
    // Add in the developer token.
    var devToken = ET.SubElement(header, 'DeveloperToken');
    devToken.text = developerToken;
    // Add in the user name.
    var uName = ET.SubElement(header, 'UserName');
    uName.text = userName;
    // Add in the password.
    var pwd = ET.SubElement(header, 'Password');
    pwd.text = password;
    // Add in the customer account ID.
    var accountId = ET.SubElement(header, 'CustomerAccountId');
    accountId.text = customerAccountId;
    // Add in the customer Customer ID.
    var custId = ET.SubElement(header, 'CustomerId');
    custId.text = customerId;
    // Create the body element.
    var body = ET.SubElement(root, 's:Body');
    body.set('xmlns', SOAP.ns_bingads);
    // Create the GetCampaignsByAccountIdRequest element.
    // var getCampaignsByAccountIdRequest = ET.SubElement(body, 'GetCampaignsByAccountIdRequest');
    var getCampaignsByAccountIdRequest = ET.SubElement(body, action + 'Request');
    // Add in the account ID.
    var bodyAccId = ET.SubElement(getCampaignsByAccountIdRequest, 'AccountId');
    bodyAccId.text = customerAccountId;
    return ET.tostring(root, {
        xml_declaration: false
    });
};